<?php
namespace app\system\controller;

use app\common\UserModel;
use dingtalk\Auth;
use think\Controller;
use think\Cookie;
use think\Request;

class PublicController extends Controller
{
    private $accessToken;
    private $jsTicket;
    private $dingtalkConfig;
    private $userModel;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->accessToken=Auth::getAccessToken();
        $this->jsTicket=Auth::getTicket($this->accessToken);
        $this->dingtalkConfig = Auth::getConfig();
        $this->userModel = new UserModel();
    }

    /**
     * 获取授权用户
     * @return mixed
     */
    public function auth()
    {
        if($this->request->isPost()){
            $code = $this->request->param('code');
            $response = Auth::getUserId($this->accessToken,$code);
            if($response['errcode']!=0){
                $this->error('errmsg');
            }
            $userinfo = $this->userModel->where('userid',$response['userid'])->find();
            if($userinfo['role_id']>0){
                Cookie::set('user',$userinfo->toArray(),3600*24);
                $this->success('操作成功！');
            }else{
                $this->error('['.$userinfo['name'].']没有操作权限！');
            }
        }
        if(Cookie::has('user')){
            $this->redirect('Index/index');
        }else{
            $this->assign('auth_config',$this->dingtalkConfig);
            return $this->fetch();
        }
    }

    /**
     * 清除登录信息
     */
    public function clearCookie(){
        Cookie::delete('user');
        $this->success('清除登录信息！');
    }

}
